import json

import pymysql


def load_json():
    with open('movie.json', 'rb') as cities_json_file:
        result = cities_json_file.read()
        result_str = result.decode('utf-8')
        print(result_str)
        result_json = json.loads(result_str)
        print(result_json)
        return result_json


def insert_movie(movie_json):
    # 参数就是城市的json对象
    movies = movie_json.get('returnValue')
    db = pymysql.Connect(host='127.0.0.1', port=3306, user='root', password='', database='tpp')
    cursor = db.cursor()
    for movie in movies:
        mid = movie.get('id', 0)
        show_name = movie.get('showName', '')
        show_name_en = movie.get('showNameEn', '')
        director = movie.get('director', '')
        leading_role = movie.get('leadingRole', '')
        type1 = movie.get('type', '')
        country = movie.get('country', '')
        language = movie.get('language', '')
        duration = movie.get('duration', '')
        openday = movie.get('openDay', '')
        poster = movie.get('poster', '')
        showVersion = movie.get('showVersion', '2D')
        if isinstance(showVersion, list):
            showVersion = showVersion[0]

        sql = "insert into movie(id,showname,shownameen,director,leadingRole,type,country,language,duration,openday,poster,orderCount,showVersion,flag) " \
              "values( %d,'%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, date('%s'), '%s', %d, '%s',%d);"

        cursor.execute(sql % (
        mid, show_name, show_name_en, director, leading_role, type1, country, language, duration, openday, poster, 0,
        showVersion, 0))
        db.commit()


if __name__ == '__main__':
    movie_json = load_json()
    insert_movie(movie_json)
